package com.zzyl.nursing.service.impl;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zzyl.nursing.service.WechatService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;

@Service
public class WechatServiceImpl implements WechatService {


    // 登录
    private static final String OPPID_URL = "https://api.weixin.qq.com/sns/jscode2session";

    // 获取token
    private static final String TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token";

    // 获取手机号
    private static final String PHONE_REQUEST_URL = "https://api.weixin.qq.com/wxa/business/getuserphonenumber";


    @Value("${wechat.appId}")
    private String appid;

    @Value("${wechat.appSecret}")
    private String secret;


    /**
     * 获取openid
     * @param code
     * @return
     */
    @Override
    public String getOpenid(String code) {
        //?grant_type=authorization_code
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("appid",appid);
        paramMap.put("secret",secret);
        paramMap.put("js_code",code);
        paramMap.put("grant_type","authorization_code");
        HttpResponse response = HttpRequest.get(OPPID_URL)
                .form(paramMap)
                .execute();
        String body = response.body();
        JSONObject jsonObject = JSONUtil.parseObj(body);

        Integer errode = (Integer) jsonObject.get("errcode");
        if(errode!=null&&errode!=0){
            throw new RuntimeException("生成openID失败:"+jsonObject.toString());
        }else{
            return jsonObject.getStr("openid");
        }

    }


    /**
     * 获取手机号
     * @param phoneCode
     * @return
     */
    @Override
    public String getPhone(String phoneCode) {
        String access_token = getToken();
        if (access_token == null || access_token.isEmpty()) {
            throw new RuntimeException("获取手机号失败: access_token 无效");
        }

        // 3. 构造正确的 JSON 请求体
        JSONObject requestBody = JSONUtil.createObj();
        requestBody.set("code", phoneCode);
        String body = HttpRequest.post(PHONE_REQUEST_URL + "?access_token=" + access_token)
                .body(requestBody.toString())
                .execute().body();

        JSONObject jsonObject = JSONUtil.parseObj(body);
        Integer errcode = (Integer) jsonObject.get("errcode");

        // 完善错误判断逻辑
        if (errcode != null && errcode != 0) {
            String errmsg = jsonObject.getStr("errmsg");
            throw new RuntimeException("获取手机号失败: errcode=" + errcode + ", errmsg=" + errmsg);
        } else if (!jsonObject.containsKey("phone_info")) {
            throw new RuntimeException("获取手机号失败: 返回数据中不包含phone_info");
        } else {
            JSONObject phoneInfo = jsonObject.getJSONObject("phone_info");
            if (phoneInfo == null) {
                throw new RuntimeException("获取手机号失败: phone_info为空");
            }
            return phoneInfo.getStr("phoneNumber");
        }
    }

//    @Override
//    public String getPhone(String phoneCode) {
//        //?access_token=ACCESS_TOKEN
//        String access_token = getToken();
////        HashMap<String, Object> paraMmap = new HashMap<>();
////        paraMmap.put("access_token",paraMmap);
//////        JSONObject code = JSONUtil.parseObj(phoneCode);
//        String body = HttpRequest.post(PHONE_REQUEST_URL + "?access_token=" + access_token)
//                .body(phoneCode)
//                .execute().body();
//        JSONObject jsonObject = JSONUtil.parseObj(body);
//        Integer errcode = (Integer) jsonObject.get("errcode");
//        if(errcode!=0){
//            throw new RuntimeException("获取phone失败:"+jsonObject.getStr("errmsg"));
//        }else{
//            JSONObject phoneInfo = jsonObject.getJSONObject("phone_info");
//            String phoneNumber = phoneInfo.getStr("phoneNumber");
//            return phoneNumber;
//        }
//
//    }

    /**
     * 获取token
     * @return
     */
    private String getToken() {
        //?grant_type=client_credential&appid=APPID&secret=APPSECRET
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("grant_type","client_credential");
        paramMap.put("appid",appid);
        paramMap.put("secret",secret);
        String body = HttpRequest.get(TOKEN_URL)
                .form(paramMap)
                .execute().body();
        JSONObject jsonObject = JSONUtil.parseObj(body);
        Integer errode = (Integer) jsonObject.get("errcode");
        if(errode!=null&&errode!=0){
            throw new RuntimeException("生成openID失败:"+jsonObject.toString());
        }else{
            return jsonObject.getStr("access_token");
        }

    }
}

